<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 5.2.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/img/16x16.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/img/32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/img/16x16.png">
  <link rel="mask-icon" href="/img/logo.png" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://unpkg.com/@fortawesome/fontawesome-free@6.3.0/css/all.min.css" integrity="sha256-/4UQcSmErDzPCMAiuOiWPVVsNN2s3ZY/NsmXNcj0IFc=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://unpkg.com/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"lirifa.github.io","root":"/","images":"/images","scheme":"Mist","darkmode":true,"version":"8.15.0","exturl":false,"sidebar":{"position":"right","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"bookmark":{"enable":true,"color":"#2bb5d4","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"livere","storage":true,"lazyload":false,"nav":null,"activeClass":"livere"},"stickytabs":false,"motion":{"enable":false,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="节流（throttle）是一种常用的性能优化技术，用于限制函数在特定时间间隔内只能执行一次。当频繁触发某个事件时，节流可以确保函数不会过于频繁地执行，从而提升性能。防抖（Debounce）是一种常用的性能优化技术，用于限制函数在短时间内被频繁调用。当事件被触发后，会等待一定时间间隔，如果在这段时间内事件没有被再次触发，才会执行函数。如果在这段时间内事件又被触发，则重新开始计时。">
<meta property="og:type" content="article">
<meta property="og:title" content="js手写系列——节流函数、防抖函数">
<meta property="og:url" content="https://lirifa.github.io/js%E6%89%8B%E5%86%99%E7%B3%BB%E5%88%97%E2%80%94%E2%80%94%E8%8A%82%E6%B5%81%E5%87%BD%E6%95%B0%E3%80%81%E9%98%B2%E6%8A%96%E5%87%BD%E6%95%B0.html">
<meta property="og:site_name" content="Rafa&#39;s Blog">
<meta property="og:description" content="节流（throttle）是一种常用的性能优化技术，用于限制函数在特定时间间隔内只能执行一次。当频繁触发某个事件时，节流可以确保函数不会过于频繁地执行，从而提升性能。防抖（Debounce）是一种常用的性能优化技术，用于限制函数在短时间内被频繁调用。当事件被触发后，会等待一定时间间隔，如果在这段时间内事件没有被再次触发，才会执行函数。如果在这段时间内事件又被触发，则重新开始计时。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-02-21T09:36:43.000Z">
<meta property="article:modified_time" content="2021-02-22T07:26:03.000Z">
<meta property="article:author" content="Rafa">
<meta property="article:tag" content="js">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://lirifa.github.io/js%E6%89%8B%E5%86%99%E7%B3%BB%E5%88%97%E2%80%94%E2%80%94%E8%8A%82%E6%B5%81%E5%87%BD%E6%95%B0%E3%80%81%E9%98%B2%E6%8A%96%E5%87%BD%E6%95%B0.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://lirifa.github.io/js%E6%89%8B%E5%86%99%E7%B3%BB%E5%88%97%E2%80%94%E2%80%94%E8%8A%82%E6%B5%81%E5%87%BD%E6%95%B0%E3%80%81%E9%98%B2%E6%8A%96%E5%87%BD%E6%95%B0.html","path":"js手写系列——节流函数、防抖函数.html","title":"js手写系列——节流函数、防抖函数"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>js手写系列——节流函数、防抖函数 | Rafa's Blog</title>
  

  <script src="/js/third-party/analytics/baidu-analytics.js"></script>
  <script async src="https://hm.baidu.com/hm.js?e65b95711a0ae7fa2a5d53e3186cff24"></script>







  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Rafa's Blog</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">角落</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li><li class="menu-item menu-item-留言"><a href="/guestbook/" rel="section"><i class="fa fa-book fa-fw"></i>留言</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%8A%82%E6%B5%81%E5%87%BD%E6%95%B0"><span class="nav-text">节流函数</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%8A%82%E6%B5%81%E7%9A%84%E5%9F%BA%E6%9C%AC%E6%A6%82%E5%BF%B5"><span class="nav-text">节流的基本概念</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text">应用场景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0"><span class="nav-text">实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E5%BB%BA%E8%AE%AE"><span class="nav-text">使用建议</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E9%98%B2%E6%8A%96%E5%87%BD%E6%95%B0"><span class="nav-text">防抖函数</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%98%B2%E6%8A%96%E7%9A%84%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5"><span class="nav-text">防抖的核心概念</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%98%B2%E6%8A%96%E7%9A%84%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86"><span class="nav-text">防抖的工作原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%98%B2%E6%8A%96%E7%9A%84%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text">防抖的应用场景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0-1"><span class="nav-text">实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%98%B2%E6%8A%96%E4%B8%8E%E8%8A%82%E6%B5%81%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="nav-text">防抖与节流的区别</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%B6%89%E5%8F%8A%E7%9F%A5%E8%AF%86%E7%82%B9"><span class="nav-text">涉及知识点</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Rafa"
      src="https://avatars.githubusercontent.com/u/44889418?v=4">
  <p class="site-author-name" itemprop="name">Rafa</p>
  <div class="site-description" itemprop="description">角落</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">10</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">3</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/lirifa" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;lirifa" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:rafa_im@163.com" title="E-Mail → mailto:rafa_im@163.com" rel="noopener me" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://lirifa.github.io/js%E6%89%8B%E5%86%99%E7%B3%BB%E5%88%97%E2%80%94%E2%80%94%E8%8A%82%E6%B5%81%E5%87%BD%E6%95%B0%E3%80%81%E9%98%B2%E6%8A%96%E5%87%BD%E6%95%B0.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://avatars.githubusercontent.com/u/44889418?v=4">
      <meta itemprop="name" content="Rafa">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Rafa's Blog">
      <meta itemprop="description" content="角落">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="js手写系列——节流函数、防抖函数 | Rafa's Blog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          js手写系列——节流函数、防抖函数
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-02-21 17:36:43" itemprop="dateCreated datePublished" datetime="2021-02-21T17:36:43+08:00">2021-02-21</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2021-02-22 15:26:03" itemprop="dateModified" datetime="2021-02-22T15:26:03+08:00">2021-02-22</time>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>3.8k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>3 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p>节流（throttle）是一种常用的性能优化技术，用于限制函数在特定时间间隔内只能执行一次。当频繁触发某个事件时，节流可以确保函数不会过于频繁地执行，从而提升性能。<br>防抖（Debounce）是一种常用的性能优化技术，用于限制函数在短时间内被频繁调用。当事件被触发后，会等待一定时间间隔，如果在这段时间内事件没有被再次触发，才会执行函数。如果在这段时间内事件又被触发，则重新开始计时。</p>
<a id="more"></a>

<h1 id="节流函数"><a href="#节流函数" class="headerlink" title="节流函数"></a>节流函数</h1><h2 id="节流的基本概念"><a href="#节流的基本概念" class="headerlink" title="节流的基本概念"></a>节流的基本概念</h2><p>节流的核心思想是：<strong>在一定时间间隔内，无论事件触发多少次，函数只会执行一次。</strong></p>
<p>与防抖(debounce)不同，防抖是在事件停止触发后延迟执行，而节流是保证在固定时间间隔内至少执行一次。</p>
<h2 id="应用场景"><a href="#应用场景" class="headerlink" title="应用场景"></a>应用场景</h2><ul>
<li>窗口大小调整(resize)事件</li>
<li>页面滚动(scroll)事件</li>
<li>鼠标移动(mousemove)事件</li>
<li>输入框实时搜索(减少请求频率)</li>
</ul>
<h2 id="实现"><a href="#实现" class="headerlink" title="实现"></a>实现</h2><ol>
<li>基础时间戳版节流</li>
</ol>
<ul>
<li>使用时间戳判断是否达到执行间隔</li>
<li>第一次会立即执行</li>
<li>停止触发后不会再次执行<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">throttleBasic</span>(<span class="params">func, delay</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> lastTime = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> (<span class="params">...args</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">const</span> currentTime = <span class="built_in">Date</span>.now();</span><br><span class="line">        <span class="keyword">if</span> (currentTime - lastTime &gt;= delay) &#123;</span><br><span class="line">            func.apply(<span class="built_in">this</span>, args);</span><br><span class="line">            lastTime = currentTime;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<ol start="2">
<li>定时器版节流</li>
</ol>
<ul>
<li>使用定时器延迟执行</li>
<li>第一次不会立即执行</li>
<li>停止触发后会再执行一次<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">throttleTimer</span>(<span class="params">func, delay</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> timeoutId = <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (!timeoutId) &#123;</span><br><span class="line">            timeoutId = <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">                func.apply(<span class="built_in">this</span>, args);</span><br><span class="line">                timeoutId = <span class="literal">null</span>;</span><br><span class="line">            &#125;, delay);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<ol start="3">
<li>完整版节流（结合时间戳和定时器）</li>
</ol>
<ul>
<li>结合时间戳和定时器</li>
<li>可配置是否立即执行（leading）和停止后是否执行（trailing)</li>
<li>功能最完整，适用性最广<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">throttle</span>(<span class="params">func, delay, options = &#123;&#125;</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 函数签名和变量声明</span></span><br><span class="line">    <span class="comment">// func: 需要被节流的原始函数</span></span><br><span class="line">    <span class="comment">// delay: 节流时间间隔（毫秒）</span></span><br><span class="line">    <span class="comment">// options: 配置对象，包含 leading 和 trailing 选项</span></span><br><span class="line">    <span class="comment">// timeoutId: 存储定时器ID，用于取消定时器</span></span><br><span class="line">    <span class="comment">// lastTime: 记录上一次函数执行的时间戳</span></span><br><span class="line">    <span class="comment">// leading: 是否在节流开始时立即执行（默认true）</span></span><br><span class="line">    <span class="comment">// trailing: 是否在节流结束后执行（默认true）</span></span><br><span class="line">    <span class="keyword">let</span> timeoutId, lastTime = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">const</span> &#123; leading = <span class="literal">true</span>, trailing = <span class="literal">true</span> &#125; = options;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 返回的节流函数</span></span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">        <span class="comment">// 保存原始函数的this上下文和参数</span></span><br><span class="line">        <span class="keyword">const</span> currentTime = <span class="built_in">Date</span>.now();</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 处理leading=false的情况, 如果是第一次调用且leading为false，设置lastTime为当前时间, 这样第一次调用不会立即执行</span></span><br><span class="line">        <span class="keyword">if</span> (!lastTime &amp;&amp; !leading) lastTime = currentTime;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 计算距离下一次可以执行函数还剩余多少时间, currentTime - lastTime是距离上次执行经过的时间</span></span><br><span class="line">        <span class="keyword">const</span> remainingTime = delay - (currentTime - lastTime);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 判断是否需要立即执行</span></span><br><span class="line">        <span class="comment">// remainingTime &lt;= 0: 已经超过了节流间隔，可以立即执</span></span><br><span class="line">        <span class="comment">// remainingTime &gt; delay: 处理特殊情况（如系统时间被修改）</span></span><br><span class="line">        <span class="keyword">if</span> (remainingTime &lt;= <span class="number">0</span> || remainingTime &gt; delay) &#123;</span><br><span class="line">            <span class="keyword">if</span> (timeoutId) &#123;</span><br><span class="line">                <span class="comment">// 清除可能存在的定时器</span></span><br><span class="line">                <span class="built_in">clearTimeout</span>(timeoutId);</span><br><span class="line">                timeoutId = <span class="literal">null</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 立即执行原始函数</span></span><br><span class="line">            func.apply(<span class="built_in">this</span>, args);</span><br><span class="line">            <span class="comment">// 更新最后执行时间</span></span><br><span class="line">            lastTime = currentTime;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (!timeoutId &amp;&amp; trailing) &#123;</span><br><span class="line">            <span class="comment">//  设置延迟执行</span></span><br><span class="line">            <span class="comment">// !timeoutId: 确保不会重复设置定时器</span></span><br><span class="line">            <span class="comment">// trailing: 配置允许在节流结束后执行</span></span><br><span class="line">            timeoutId = <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">                func.apply(<span class="built_in">this</span>, args);</span><br><span class="line">                lastTime = <span class="built_in">Date</span>.now();</span><br><span class="line">                timeoutId = <span class="literal">null</span>;</span><br><span class="line">            &#125;, remainingTime);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h2 id="使用建议"><a href="#使用建议" class="headerlink" title="使用建议"></a>使用建议</h2><ul>
<li>对于需要立即响应的场景（如按钮点击），使用基础时间戳版</li>
<li>对于需要保证最后一次执行的场景，使用定时器版</li>
<li>大多数情况下，推荐使用完整版，因为它提供了最灵活的控制选项</li>
</ul>
<h1 id="防抖函数"><a href="#防抖函数" class="headerlink" title="防抖函数"></a>防抖函数</h1><h2 id="防抖的核心概念"><a href="#防抖的核心概念" class="headerlink" title="防抖的核心概念"></a>防抖的核心概念</h2><p>防抖的核心思想是：在事件被触发后，等待一定时间间隔，如果在这段时间内事件没有被再次触发，才会执行函数。如果在这段时间内事件再次被触发，则重新计时。</p>
<h2 id="防抖的工作原理"><a href="#防抖的工作原理" class="headerlink" title="防抖的工作原理"></a>防抖的工作原理</h2><ol>
<li>事件触发时，设置一个定时器</li>
<li>如果在定时器结束前事件再次触发，则清除之前的定时器并重新设置</li>
<li>只有当事件停止触发一段时间后，函数才会执行</li>
</ol>
<h2 id="防抖的应用场景"><a href="#防抖的应用场景" class="headerlink" title="防抖的应用场景"></a>防抖的应用场景</h2><ul>
<li>搜索框输入建议</li>
<li>窗口大小调整(resize)事件</li>
<li>表单验证</li>
<li>按钮点击防重复提交</li>
<li>自动保存功能</li>
</ul>
<h2 id="实现-1"><a href="#实现-1" class="headerlink" title="实现"></a>实现</h2><ol>
<li>基础防抖函数<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">debounceBasic</span>(<span class="params">func, delay</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> timeoutId;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">        <span class="comment">// 清除之前的定时器</span></span><br><span class="line">        <span class="built_in">clearTimeout</span>(timeoutId);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 设置新的定时器</span></span><br><span class="line">        timeoutId = <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            func.apply(<span class="built_in">this</span>, args);</span><br><span class="line">        &#125;, delay);</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>立即执行版防抖函数<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">debounceImmediate</span>(<span class="params">func, delay, immediate = <span class="literal">false</span></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> timeoutId;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">const</span> context = <span class="built_in">this</span>;</span><br><span class="line">        <span class="keyword">const</span> callNow = immediate &amp;&amp; !timeoutId;</span><br><span class="line">        </span><br><span class="line">        <span class="built_in">clearTimeout</span>(timeoutId);</span><br><span class="line">        </span><br><span class="line">        timeoutId = <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            timeoutId = <span class="literal">null</span>;</span><br><span class="line">            <span class="keyword">if</span> (!immediate) &#123;</span><br><span class="line">                func.apply(context, args);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, delay);</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> (callNow) &#123;</span><br><span class="line">            func.apply(context, args);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>增强版防抖函数<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">debounceEnhanced</span>(<span class="params">func, delay, options = &#123;&#125;</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> timeoutId;</span><br><span class="line">    <span class="keyword">let</span> lastExecTime = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">let</span> leading = options.leading || <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">let</span> trailing = options.trailing !== <span class="literal">false</span>; <span class="comment">// 默认true</span></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">const</span> context = <span class="built_in">this</span>;</span><br><span class="line">        <span class="keyword">const</span> currentTime = <span class="built_in">Date</span>.now();</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 立即执行逻辑</span></span><br><span class="line">        <span class="keyword">if</span> (leading &amp;&amp; !timeoutId) &#123;</span><br><span class="line">            func.apply(context, args);</span><br><span class="line">            lastExecTime = currentTime;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="built_in">clearTimeout</span>(timeoutId);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 延迟执行逻辑</span></span><br><span class="line">        <span class="keyword">if</span> (trailing) &#123;</span><br><span class="line">            timeoutId = <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">                func.apply(context, args);</span><br><span class="line">                lastExecTime = <span class="built_in">Date</span>.now();</span><br><span class="line">                timeoutId = <span class="literal">null</span>;</span><br><span class="line">            &#125;, delay);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>


</li>
</ol>
<h2 id="防抖与节流的区别"><a href="#防抖与节流的区别" class="headerlink" title="防抖与节流的区别"></a>防抖与节流的区别</h2><table>
<thead>
<tr>
<th>特性</th>
<th>防抖(Debounce)</th>
<th>节流(Throttle)</th>
</tr>
</thead>
<tbody><tr>
<td>执行时机</td>
<td>在事件停止触发后执行</td>
<td>在固定时间间隔内执行</td>
</tr>
<tr>
<td>执行次数</td>
<td>只执行最后一次</td>
<td>至少执行一次</td>
</tr>
<tr>
<td>适用场景</td>
<td>搜索框输入、窗口调整</td>
<td>页面滚动、鼠标移动</td>
</tr>
</tbody></table>
<h1 id="涉及知识点"><a href="#涉及知识点" class="headerlink" title="涉及知识点"></a>涉及知识点</h1><ul>
<li><a href="https://lirifa.github.io/js%E4%B8%AD%E7%9A%84%E9%97%AD%E5%8C%85.html">闭包</a></li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/js/" rel="tag"><i class="fa fa-tag"></i> js</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/js%E4%B8%AD%E7%9A%84%E9%97%AD%E5%8C%85.html" rel="prev" title="js中的闭包">
                  <i class="fa fa-chevron-left"></i> js中的闭包
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/js%E4%B8%AD%E7%9A%84%E5%8E%9F%E5%9E%8B%E4%B8%8E%E5%8E%9F%E5%9E%8B%E9%93%BE.html" rel="next" title="js中的原型与原型链">
                  js中的原型与原型链 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments" id="lv-container" data-id="city" data-uid="MTAyMC82MDk1Ni8zNzQyNg=="></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Rafa</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">38k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">34 分钟</span>
  </span>
</div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script size="100" alpha="0.3" zIndex="-1" src="https://unpkg.com/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="https://unpkg.com/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://unpkg.com/jquery@3.6.3/dist/jquery.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
  <script src="https://unpkg.com/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" integrity="sha256-yt2kYMy0w8AbtF89WXb2P1rfjcP/HTHLT7097U8Y5b8=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script><script src="/js/bookmark.js"></script>

  <script src="https://unpkg.com/hexo-generator-searchdb@1.4.1/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>



  <script src="/js/third-party/fancybox.js"></script>


  




<script src="/js/third-party/comments/livere.js"></script>

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"left","width":160,"height":280},"mobile":{"show":false},"react":{"opacityDefault":1,"opacityOnHover":1},"log":false,"tagMode":false});</script></body>
</html>
